- Notifications
You must be signed in to change notification settings - Fork 366
/
Copy pathEdit distance leetcode
22 lines (20 loc) · 749 Bytes
/
Edit distance leetcode
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
//link: https://leetcode.com/problems/edit-distance/description/
int solve(int i, int j, string s1, string s2,vector<vector<int>>& dp){
//base case
if(j<0) return i+1;
if(i<0) return j+1;
if(dp[i][j]!=-1) return dp[i][j];
if(s1[i] == s2[j]){
return dp[i][j] = solve(i-1,j-1,s1,s2,dp);
}
int del = solve(i-1,j,s1,s2,dp);
int rp = solve(i-1,j-1,s1,s2,dp);
int ins = solve(i,j-1,s1,s2,dp);
return dp[i][j] =1+ min({del,rp,ins});
}
int minDistance(string word1, string word2) {
int n = word1.length();
int m = word2.length();
vector<vector<int>> dp(n+1,vector<int>(m+1,-1));
return solve(n-1,m-1,word1,word2,dp);
}